package sht.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import sht.commons.ParamUtil;
import sht.dao.Dao;

@Repository
@Transactional//自动管理通过Hibernate获取的当前session
public class DaoImpl implements Dao{
	
	@Autowired
	private HibernateTemplate hibernateTemplate;

	public Session getSession () {
		return hibernateTemplate.getSessionFactory().getCurrentSession();
	}
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	@Override
	public void presit(Object entity){
		hibernateTemplate.persist(entity);
	}
	@Override
	public void save(Object entity) {
		hibernateTemplate.save(entity);
	}

	@Override
	public void delete(Object entity) {
		hibernateTemplate.delete(entity);
	}

	@Override
	public void update(Object entity) {
		hibernateTemplate.update(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> find(String sql,Object[] params){
		return (List<T>) hibernateTemplate.find(sql, params);
	}

	@Override
	public List<?> findNamedQuery(String queryName,Object...params){
		return hibernateTemplate.findByNamedQuery(queryName, params);
	}
	
	@Override
	public List<?> findNamedParam(String queryString,String[] paramNames, Object[] values){
		return hibernateTemplate.findByNamedParam(queryString, paramNames, values);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> getQueryList(String hsql,Map<String, Object> mapParam) {
		Query query = getSession().createQuery(hsql);
		mapParam.forEach((k,v) ->{
			ParamUtil.parseParam(query,k,v);
		});
		return query.list();
	}
	
}
